#include "stdio.h"
#include "CompressRLE.h"

CompressRLE::CompressRLE(void)
{
	
}


char * CompressRLE::ReadFile(char* path) //read file source and copy data to (char *sourcefile)
{
	
	FILE *file=fopen(path,"rb");
	if(!file) return NULL;
	
	//get size of file
	fseek(file,0L,SEEK_END);
	size=ftell(file);
	fseek(file,0L,0);

	char*sourcefile=new char[size];
		
	fread(sourcefile,1,size,file);
	fclose(file);
	
	return sourcefile;
}
int CompressRLE::CountTheNumBerOfDigits(int Num) //count number of digitsv ex 10 is 2, 100 is 3
{
	int size=0;

	while(Num>0)
	{
		Num=Num/10;
		size++;
	}
	return size;
}
char* CompressRLE::Compress(char* path) //Compress file use RLE
{
	int i=0;
	int k=0;
	int j=0;
	int count=0;
	int numberofdigit=0;
	
	char*sourcefile=ReadFile(path);
	char *buffer=new char[size*2]; 

	buffer[size*2-1]=0;
	while (buffer[i]!=NULL) //clear buffer
	{
		buffer[i]=0;
		i++;
	}

	i=0;
	while (true)
	{
		while(i>=1 && sourcefile[i]==sourcefile[i-1]&&sourcefile[i]!=0) i=i+1;
		if(i>=size) break;

		count=0;

		if(sourcefile[i]==sourcefile[i+1])
		{
		
				buffer[k]=sourcefile[i];
				j=i;
				while (true)
				{
					if(sourcefile[i]==sourcefile[j+1]) count++;
					j=j+1;
					if(sourcefile[j]==NULL||sourcefile[i]!=sourcefile[j+1]) break;
				}			
		}
		else 
			buffer[k]=sourcefile[i];

		i=i+1;
		k=k+1;
		count=count+1;
		numberofdigit=CountTheNumBerOfDigits(count);

		if(count>=0)
		{

			if(count>9&&count<100)  
			{
				
				buffer[k]=count/10;
				buffer[k+1]=count%10;
						
			}				
			else 
			{
				buffer[k]=(char)count;
	
			}
				
			k=k+numberofdigit;
		}
		
	}
	
	delete[] sourcefile;
	sourcefile=NULL;
	

	return buffer;
}
void CompressRLE::WriteFile(char* pathsource,char* pathdest) //write file compressed 
{
	int i=0;
	char*combuffer;
	combuffer=Compress(pathsource);

	for(i=0;i<=2*size;i++)
	{
		if(combuffer[i]==0) break;
	}
	
	FILE *file=fopen(pathdest,"w");
	if(file)
	{
		fwrite(combuffer,i,1,file);
		fclose(file);
	}

		puts(combuffer);

		delete []combuffer;
		combuffer=NULL;
		
		
		
}
void CompressRLE::Extract(char* pathsource,char* pathdest) 
{
	int i=0;	
	int count=0;
	int size=0;
	int mul=1;

	char* sourcefile;

	sourcefile=ReadFile(pathsource);
	puts(sourcefile);

	FILE *file=fopen(pathdest,"w");
	if(file)
	{
	
		while (sourcefile[i]!=NULL)
		{
			count=0;
			mul=1;
			while(i%2!=0)
			{
	
					count=(sourcefile[i])+count*mul;
					i++;
					mul=10;

					if(i%2==0) break;
			}
				if(file)
				{
					for(int j=0;j<count;j++)
					{
						putc(sourcefile[i-CountTheNumBerOfDigits(count)-1],file);
				
					}
				}
				i++;
	
			}

			fclose(file);
	}
	
	sourcefile=NULL;
	delete[] sourcefile;
}
CompressRLE::~CompressRLE(void)
{
	
}
